<?php
namespace App\Repositories\System;
use App\Common\Utils\BaseRepository;
use App\Models\ActivityInfo;
use App\Models\DecSubject;
use App\Models\File;
use App\Models\System\Dicitem;
use Illuminate\Support\Facades\Log;

/**
 * 活动信息
 */
class ActivityRepository extends BaseRepository
{
    /** @var \App\Repositories\System\DictionaryItemRepository $dictionaryItemRepository */
    private $dictionaryItemRepository;

    protected $model;

    public function __construct(ActivityInfo $activity)
    {
        $this->model = $activity;
        $this->dictionaryItemRepository = app('dictionaryItemRepository');
    }

    /**
     * @Description: 数据处理
     * @Author: kzj
     * @datetime: 2023-02-28
     */
    public function dealRequestData($d)
    {
        $activity = [];
        $dicMultiple = []; //多选处理
        $dicItems = [];
        $dicIds = [];
        $files = [];
        $dicCodes = [];

        if($d['activity_category'] == 'TEARRESEARCH_DEVELOP_SUBJECT_TABLE' && (isset($d['grade_dic_ids']) && $d['grade'])) {
            unset($d['grade']);
        }
        if($d['activity_category'] == 'TEACHERTRAINING_JOINTRAINING_TABLE' && (isset($d['grade_dic_ids']) && $d['grade_item'])) {
            unset($d['grade_item']);
        }
        if($d['activity_category'] == 'TEACHERTRAINING_ACTIVITY_TABLE' && (isset($d['course_dic_ids']) && $d['course_item'])) {
            unset($d['course_item']);
        }
        if($d['activity_category'] == 'TEARRESEARCH_DEVELOP_SUBJECT_TABLE'){
            $courseResponse = Dicitem::select('id', 'diccode', 'itemcode', 'itemname')->where('diccode', 'KMLB')->get();
            $courseArray = array_column($courseResponse->toArray(),'itemname','itemcode');
            $courseData = [['order' => 0,'optionId' => $d['course'],'parentId' => 0,'selectKey' => '','selectValue' => $courseArray[$d['course']]]];
            unset($d['course']);
        }
        // dd($d);
        foreach($d as $k => $item) {
            switch($k) {
                case "data_version_id":
                case "activity_category":
                case "name":
                case "participant_object":
                case "remark":
                case "witness_position":
                case "head_of_departs":
                case "customer_grade":
                case "award_from":
                case "teacher_name":
                case "school_name":
                case "periodical":
                case "is_published":
                case "is_core":
                case "is_awarded":
                case "stage":
                case "is_wsjl":
                case "wsjl_info":
                case "other_paper":
                case "treatise_type":
                case "zmd_remark":
                case "jyz_code":
                case "zm_style":
                case "zm_gkk_category":
                case "is_young_teachers":
                case "place":
                case "target":
                    $activity[$k] = $item ? $item : '';
                    break;
                case "date":
                case "begin_date":
                case "end_date":
                    $activity[$k] = $item ? $item : null;
                    break;
                case "pubications_publish_type":
                    if($d['activity_category'] == 'TEARRESEARCH_DEVELOP_SUBJECT_TABLE') {
                        $dicCodes[$k] = ['diccode' => 'KMLB', 'itemcode' => $item];
                        break;
                    } else {
                        $dicItems[$item] = $k;
                        $dicIds[] = $item;
                        break;
                    }
                case "level":
                case "course":
                case "grade":
                case "class_item":
                case "witness":
                case "awarding_unit":
                case "guided_teacher":
                case "guided_teacher_school":
                case "reception_class":
                case "category":
                    $dicItems[$item] = $k;
                    $dicIds[] = $item;
                    break;
                case "files":
                    $files = $item;
                    break;
                case "grade_dic_ids":
                    foreach($item as $k => $v) {
                        $dicIds[] = $v;
                    }
                    $dicMultiple['grade'] = $item;
                    break;
                case "course_dic_ids":
                    foreach($item as $k => $v) {
                        $dicIds[] = $v;
                    }
                    $dicMultiple['course'] = $item;
                    break;
                case "zmr":
                    $activity['witness'] = $item ? json_encode(array('zmr' => $item)) : '';
                case "fzr":
                    $activity['head_of_departs'] = $item ? $item : '';

            }
        }
        foreach($activity as $k => $item) {
            if(empty($item)) {
                unset($activity[$k]);
            }
        }

         //dd($dicIds,$dicItems,$dicMultiple, $d);
        //字典数据处理
        if(!empty($dicIds)) {
            $dicArr = $this->dictionaryItemRepository->getDictionaryItem($dicIds);

            if($dicArr->count()) {
                if(!empty($dicItems)) {
                    foreach($dicItems as $id => $field) {
                        if($field == 'course' && $d['activity_category'] != 'TEARRESEARCH_DEVELOP_SUBJECT_TABLE') {//学科处理
                            $decSubject = DecSubject::query()->select('id as optionId','name as selectValue','name as selectKey')
                                ->where('id', $id)->first();
                            if($decSubject) {
                                $decSubject->parentId = 0;
                                $decSubject->order = 0;
                                $activity['course'] = json_encode([$decSubject->toArray()]);
                            }
                        }else {
                            $dicInfo = $dicArr->where('optionId', $id)->first();
                            //dd($dicInfo->toArray());
                            if ($dicInfo) {
                                $activity[$field] = json_encode([$dicInfo->toArray()]);
                            }
                        }
                    }
                }
                if(!empty($dicMultiple)) {
                    foreach($dicMultiple as $field => $ids) {
                        $dicInfo = $dicArr->whereIn('optionId', $ids);
                        if ($dicInfo) {
                            $activity[$field] = json_encode($dicInfo->toArray());
                        }
                    }
                }
            }
            if(!empty($dicMultiple)) {
                foreach ($dicMultiple as $field => $ids) {
                    if ($field == 'course') {//学科处理
                        $decSubject = DecSubject::query()->select('id as optionId', 'name as selectValue', 'name as selectKey')
                            ->whereIn('id', $ids)->get();
                        if ($decSubject) {
                            $decSubject->parentId = 0;
                            $decSubject->order = 0;
                            $activity['course'] = json_encode($decSubject->toArray());
                        }
                    }
                }
            }
        }
        if(!empty($dicCodes)) {
            foreach($dicCodes as $field => $v) {
                $dicCodeInfo = Dicitem::select('id', 'diccode', 'itemcode', 'itemname')->where('diccode', $v['diccode'])->where('itemcode', $v['itemcode'])->first();

                if($dicCodeInfo) {
                    $activity[$field] = json_encode([$dicCodeInfo->toArray()]);
                }
            }
        }

        //上传文件处理
        if(!empty($files)) {
            $proofMaterial = $this->dealUploadFile($files);

            if(!empty($proofMaterial)) {
                $activity['proof_material'] = json_encode($proofMaterial);
            }
        }
        if($d['activity_category'] == 'TEARRESEARCH_DEVELOP_SUBJECT_TABLE') {
            $activity['course'] = json_encode($courseData);
        }

        return $activity;
    }

    public function dealUploadFile($files) {
        $result = [];
        // dd($files, $id);
        foreach($files as $field => $file) {
            if(!$file) {
                continue;
            }

            $currentFiles = json_decode($file);
            // dd($currentFiles);
            foreach($currentFiles as $cf) {
                if(!$cf) {
                    continue;
                }

                if(isset($cf->id)) {
                    $file = File::whereId($cf->id)->first();

                    $result[] = [
                        'id'        => $cf->id,
                        'editable'  => true,
                        'fileName'  => $cf->file_name,
                        'filePath'  => $file->id.'/'.$file->file_key,
                        'extension' => $file->extension,
                        'files_id' => $cf->files_id ?? '',
                        'field'     => $field
                    ];
                    continue;
                }

                $url = explode('/', $cf->url);

                if(isset($url[5])){
                    $ext = explode('.', $url[5]);
                    $fileObj = File::create([
                        'file_name' => $cf->file_name,
                        'file_key'  => $ext[0],
                        'extension' => $ext[1],
                        'file_path' => $url[3].'/'.$url[4].'/'.$url[5],
                        'file_dir'  => '/back-end/uploadfiles/',
                        'file_size' => $cf->size
                    ]);

                    $result[] = [
                        'id'        => $fileObj->id,
                        'editable'  => true,
                        'fileName'  => $cf->file_name,
                        'filePath'  => $fileObj->id.'/'.$ext[0],
                        'extension' => $ext[1],
                        'files_id' => $cf->files_id ?? '',
                        'field'     => $field
                    ];
                }else{
                    //老数据处理 - 老数据无需处理

                }


            }
        }
        // dd($result);
        return $result;
    }


    public function getViewPower($formKey)
    {
        $roleId = 0;
        switch($formKey) {
            case "TEARRESEARCH_OPEN_TABLE":
                $roleId = 217;
                break;
            case "TEARRESEARCH_EXCHANGE_TABLE":
                $roleId = 222;
                break;
            case "EW_EXCHANGE_EXPERIENCE_TABLE":
                $roleId = 222;
                break;
            case "TEARRESEARCH_SUBJECT_STUDY_TABLE":
                $roleId = 227;
                break;
            case "EW_SUBJECT_RESEARCH_TABLE":
                $roleId = 227;
                break;
            case "TEARRESEARCH_PUBLISH_TABLE":
                $roleId = 238;
                break;
            case "EW_PAPER_PUBLISH_TABLE":
                $roleId = 233;
                break;
            case "TEARRESEARCH_DEVELOP_SUBJECT_TABLE":
                $roleId = 243;
                break;
            case "EW_SOCIAL_PRACTICE_TABLE":
                $roleId = 270;
                break;
            case "EW_CLASS_MEETING_TABLE":
                $roleId = 275;
                break;
            case "EW_THEME_ACTIVITY_TABLE":
                $roleId = 280;
                break;
            case "TEACHERTRAINING_DEVELOPCOURSE_TABLE":
                $roleId = 285;
                break;
            case "TEACHERTRAINING_OUTTRAINING_TABLE":
                $roleId = 292;
                break;
            case "TEACHERTRAINING_OTHER_TABLE":
                $roleId = 297;
                break;
            case "TEACHERTRAINING_JOINTRAINING_TABLE":
                $roleId = 313;
                break;
        }

        $result = false;
        if($roleId > 0) {
            $result = is_check($roleId);
        }

        return $result;
    }

}
